const { Payment, PAYMENT_STATUS, PAYMENT_METHOD } = require('../models/payment.model');
const Order = require('../models/order.model');
const Cart = require('../models/cart.model');
const AppError = require('../utils/AppError');
const alipayService = require('../services/alipay.service');

/**
 * 创建支付订单
 * POST /api/payments/create
 */
exports.createPayment = async (req, res, next) => {
  try {
    const { orderId, paymentMethod } = req.body;
    const userId = req.user._id;

    // 使用配置的回调地址
    const notifyUrl = process.env.PAYMENT_NOTIFY_URL || 'http://localhost:3002/api/payments/alipay/notify';
    const returnUrl = process.env.PAYMENT_RETURN_URL || 'http://localhost:3000/payment/result';

    // 验证订单
    const order = await Order.findById(orderId);
    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    if (order.user.toString() !== userId.toString()) {
      throw new AppError('无权限访问此订单', 403);
    }

    if (order.isPaid) {
      throw new AppError('订单已支付', 400);
    }

    if (order.orderStatus === '已取消') {
      throw new AppError('订单已取消，无法支付', 400);
    }

    // 检查是否已有待支付的支付记录
    const existingPayment = await Payment.findOne({
      orderId,
      status: PAYMENT_STATUS.PENDING
    });

    if (existingPayment && !existingPayment.isExpired()) {
      // 返回现有的支付记录
      return res.json({
        paymentId: existingPayment._id,
        paymentNo: existingPayment.paymentNo,
        orderId: existingPayment.orderId,
        amount: existingPayment.amount,
        paymentMethod: existingPayment.paymentMethod,
        status: existingPayment.status,
        paymentUrl: existingPayment.paymentUrl,
        qrCode: existingPayment.qrCode,
        expiresAt: existingPayment.expiresAt,
        createdAt: existingPayment.createdAt
      });
    }

    // 创建新的支付记录
    const paymentNo = Payment.generatePaymentNo();
    const amount = Math.round(order.totalPrice * 100); // 转换为分
    const expiresAt = new Date(Date.now() + 30 * 60 * 1000); // 30分钟后过期

    const payment = new Payment({
      paymentNo,
      orderId,
      userId,
      paymentMethod,
      amount,
      expiresAt
    });

    // 根据支付方式调用相应的支付服务
    let paymentResult = {};

    switch (paymentMethod) {
      case PAYMENT_METHOD.ALIPAY:
        paymentResult = await alipayService.createPayment({
          paymentNo,
          amount,
          subject: `订单支付-${order.orderNo}`,
          returnUrl,
          notifyUrl
        });
        break;

      case PAYMENT_METHOD.WECHAT:
        // TODO: 集成微信支付
        throw new AppError('微信支付暂未开放', 400);

      case PAYMENT_METHOD.UNIONPAY:
        // TODO: 集成银联支付
        throw new AppError('银联支付暂未开放', 400);

      case PAYMENT_METHOD.BALANCE:
        // TODO: 余额支付
        throw new AppError('余额支付暂未开放', 400);

      default:
        throw new AppError('不支持的支付方式', 400);
    }

    // 更新支付记录
    payment.paymentUrl = paymentResult.paymentUrl;
    payment.qrCode = paymentResult.qrCode;
    payment.thirdPartyResponse = paymentResult.rawResponse;

    await payment.save();

    res.status(201).json({
      paymentId: payment._id,
      paymentNo: payment.paymentNo,
      orderId: payment.orderId,
      amount: payment.amount,
      paymentMethod: payment.paymentMethod,
      status: payment.status,
      paymentUrl: payment.paymentUrl,
      qrCode: payment.qrCode,
      expiresAt: payment.expiresAt,
      createdAt: payment.createdAt
    });

  } catch (error) {
    next(error);
  }
};

/**
 * 查询支付状态
 * GET /api/payments/:paymentId/status
 */
exports.getPaymentStatus = async (req, res, next) => {
  try {
    const { paymentId } = req.params;
    const userId = req.user._id;

    const payment = await Payment.findById(paymentId).populate('orderId');
    if (!payment) {
      throw new AppError('支付记录不存在', 404);
    }

    if (payment.userId.toString() !== userId.toString()) {
      throw new AppError('无权限访问此支付记录', 403);
    }

    // 如果支付状态为待支付，查询第三方支付状态
    if (payment.status === PAYMENT_STATUS.PENDING && !payment.isExpired()) {
      let thirdPartyStatus = null;

      switch (payment.paymentMethod) {
        case PAYMENT_METHOD.ALIPAY:
          thirdPartyStatus = await alipayService.queryPayment(payment.paymentNo);
          break;
      }

      // 根据第三方状态更新本地状态
      if (thirdPartyStatus && thirdPartyStatus.status !== payment.status) {
        if (thirdPartyStatus.status === 'success') {
          await payment.updateStatus(PAYMENT_STATUS.SUCCESS, {
            thirdPartyTransactionId: thirdPartyStatus.transactionId,
            thirdPartyResponse: thirdPartyStatus.rawResponse
          });

          // 更新订单状态
          const order = await Order.findById(payment.orderId).populate('orderItems.product');
          if (order) {
            await order.updateStatus('待发货');
            order.paymentId = payment._id;
            await order.save();

            // 从购物车中删除已购买的商品
            const cart = await Cart.findOne({ user: order.user });
            if (cart) {
              // 获取已购买商品的ID列表
              const purchasedProductIds = order.orderItems.map(item => item.product.toString());

              // 从购物车中移除已购买的商品
              cart.items = cart.items.filter(cartItem =>
                !purchasedProductIds.includes(cartItem.product.toString())
              );

              // 重新计算购物车总计
              await cart.save(); // 会触发pre('save')钩子重新计算总计
            }
          }
        } else if (thirdPartyStatus.status === 'failed') {
          await payment.updateStatus(PAYMENT_STATUS.FAILED, {
            failureReason: thirdPartyStatus.failureReason,
            thirdPartyResponse: thirdPartyStatus.rawResponse
          });
        }
      }
    }

    res.json({
      paymentId: payment._id,
      paymentNo: payment.paymentNo,
      orderId: payment.orderId,
      amount: payment.amount,
      paymentMethod: payment.paymentMethod,
      status: payment.status,
      paidAt: payment.paidAt,
      failureReason: payment.failureReason,
      createdAt: payment.createdAt,
      expiresAt: payment.expiresAt
    });

  } catch (error) {
    next(error);
  }
};

/**
 * 支付宝回调处理
 * POST /api/payments/alipay/notify
 */
exports.handleAlipayNotify = async (req, res, next) => {
  try {
    const notifyData = req.body;

    // 验证回调签名
    const isValid = await alipayService.verifyNotify(notifyData);
    if (!isValid) {
      return res.status(400).send('FAIL');
    }

    const paymentNo = notifyData.out_trade_no;
    const payment = await Payment.findOne({ paymentNo });

    if (!payment) {
      return res.status(400).send('FAIL');
    }

    // 记录回调通知
    await payment.recordNotify();

    // 处理支付结果
    if (notifyData.trade_status === 'TRADE_SUCCESS' || notifyData.trade_status === 'TRADE_FINISHED') {
      if (payment.status !== PAYMENT_STATUS.SUCCESS) {
        // 更新支付状态
        await payment.updateStatus(PAYMENT_STATUS.SUCCESS, {
          thirdPartyTransactionId: notifyData.trade_no,
          thirdPartyResponse: notifyData
        });

        // 更新订单状态
        const order = await Order.findById(payment.orderId).populate('orderItems.product');
        if (order) {
          await order.updateStatus('待发货');
          order.paymentId = payment._id;
          await order.save();

          // 从购物车中删除已购买的商品
          const cart = await Cart.findOne({ user: order.user });
          if (cart) {
            // 获取已购买商品的ID列表
            const purchasedProductIds = order.orderItems.map(item => item.product.toString());

            // 从购物车中移除已购买的商品
            cart.items = cart.items.filter(cartItem =>
              !purchasedProductIds.includes(cartItem.product.toString())
            );

            // 重新计算购物车总计
            await cart.save(); // 会触发pre('save')钩子重新计算总计
          }
        }
      }
    } else if (notifyData.trade_status === 'TRADE_CLOSED') {
      // 支付失败
      await payment.updateStatus(PAYMENT_STATUS.FAILED, {
        failureReason: '支付已关闭',
        thirdPartyResponse: notifyData
      });
    }

    res.send('SUCCESS');

  } catch (error) {
    console.error('支付宝回调处理失败:', error);
    res.status(500).send('FAIL');
  }
};

/**
 * 取消支付
 * POST /api/payments/:paymentId/cancel
 */
exports.cancelPayment = async (req, res, next) => {
  try {
    const { paymentId } = req.params;
    const userId = req.user._id;

    const payment = await Payment.findById(paymentId);
    if (!payment) {
      throw new AppError('支付记录不存在', 404);
    }

    if (payment.userId.toString() !== userId.toString()) {
      throw new AppError('无权限访问此支付记录', 403);
    }

    if (payment.status !== PAYMENT_STATUS.PENDING) {
      throw new AppError('只能取消待支付的订单', 400);
    }

    // 更新支付状态
    await payment.updateStatus(PAYMENT_STATUS.CANCELLED);

    res.json({ message: '支付已取消' });

  } catch (error) {
    next(error);
  }
};

/**
 * 模拟支付处理（仅用于开发测试）
 * POST /api/payments/simulate
 */
exports.simulatePayment = async (req, res, next) => {
  try {
    const { orderId, success } = req.body;
    const userId = req.user._id;

    // 验证订单
    const order = await Order.findById(orderId);
    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    if (order.user.toString() !== userId.toString()) {
      throw new AppError('无权限访问此订单', 403);
    }

    if (order.isPaid) {
      throw new AppError('订单已支付', 400);
    }

    if (order.orderStatus === '已取消') {
      throw new AppError('订单已取消，无法支付', 400);
    }

    // 查找或创建支付记录
    let payment = await Payment.findOne({ orderId, status: PAYMENT_STATUS.PENDING });

    if (!payment) {
      // 创建新的支付记录
      const paymentNo = Payment.generatePaymentNo();
      const amount = Math.round(order.totalPrice * 100); // 转换为分

      payment = new Payment({
        paymentNo,
        orderId,
        userId,
        paymentMethod: 'alipay', // 模拟支付宝
        amount,
        expiresAt: new Date(Date.now() + 30 * 60 * 1000) // 30分钟后过期
      });
      await payment.save();
    }

    if (success) {
      // 模拟支付成功
      await payment.updateStatus(PAYMENT_STATUS.SUCCESS, {
        thirdPartyTransactionId: `mock_${Date.now()}`,
        thirdPartyResponse: { mock: true, timestamp: new Date() }
      });

      // 更新订单状态
      await order.updateStatus('待发货');
      order.paymentId = payment._id;
      await order.save();

      // 从购物车中删除已购买的商品
      const Cart = require('../models/cart.model');
      const cart = await Cart.findOne({ user: order.user });
      if (cart) {
        // 获取已购买商品的ID列表
        const purchasedProductIds = order.orderItems.map(item => item.product.toString());

        // 从购物车中移除已购买的商品
        cart.items = cart.items.filter(cartItem =>
          !purchasedProductIds.includes(cartItem.product.toString())
        );

        // 重新计算购物车总计
        await cart.save(); // 会触发pre('save')钩子重新计算总计
      }

      res.json({
        success: true,
        message: '模拟支付成功',
        payment,
        order: await Order.findById(orderId)
      });
    } else {
      // 模拟支付失败
      await payment.updateStatus(PAYMENT_STATUS.FAILED, {
        failureReason: '模拟支付失败',
        thirdPartyResponse: { mock: true, timestamp: new Date() }
      });

      res.json({
        success: false,
        message: '模拟支付失败',
        payment
      });
    }
  } catch (error) {
    next(error);
  }
};
